/**
 * AI写作功能Hook
 * 提供统一的AI写作接口
 */

import { useState, useCallback, useRef } from 'react'
import { EnhancedLangChainService } from '../../electron/services/EnhancedLangChainService'

// AI写作选项
export interface AIWriterOptions {
  style?: 'formal' | 'casual' | 'academic' | 'creative' | 'technical'
  tone?: 'neutral' | 'positive' | 'negative' | 'persuasive' | 'informative'
  length?: 'short' | 'medium' | 'long'
  targetWords?: number
  language?: string
  context?: string
}

// AI写作状态
export interface AIWriterState {
  isLoading: boolean
  result: string | null
  error: string | null
  progress: number
  currentAction: string
}

// AI操作类型
export type AIAction =
  | 'polish'
  | 'expand'
  | 'translate'
  | 'summarize'
  | 'continue'
  | 'generate'
  | 'fixGrammar'
  | 'changeTone'
  | 'formatMarkdown'
  | 'extractKeywords'
  | 'generateOutline'
  | 'improveSEO'

export const useAIWriter = () => {
  const [state, setState] = useState<AIWriterState>({
    isLoading: false,
    result: null,
    error: null,
    progress: 0,
    currentAction: '',
  })

  const aiServiceRef = useRef<EnhancedLangChainService | null>(null)
  const abortControllerRef = useRef<AbortController | null>(null)

  // 初始化AI服务
  const initializeAI = useCallback(async () => {
    try {
      if (!aiServiceRef.current) {
        // 在实际应用中，这里需要通过IPC调用主进程的服务
        // aiServiceRef.current = await window.electronAPI.getAIService()
        console.log('AI Service initialized')
      }
    } catch (error) {
      setState(prev => ({
        ...prev,
        error: error instanceof Error ? error.message : 'Failed to initialize AI service',
      }))
    }
  }, [])

  // 执行AI操作
  const executeAIAction = useCallback(async (
    action: AIAction,
    text: string,
    options: AIWriterOptions & { targetLang?: string } = {}
  ): Promise<string | null> => {
    // 取消之前的请求
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
    }

    abortControllerRef.current = new AbortController()

    setState(prev => ({
      ...prev,
      isLoading: true,
      error: null,
      result: null,
      progress: 0,
      currentAction: getActionDisplayName(action),
    }))

    try {
      await initializeAI()

      // 模拟进度更新
      const progressInterval = setInterval(() => {
        setState(prev => ({
          ...prev,
          progress: Math.min(prev.progress + 10, 90),
        }))
      }, 200)

      let result: string | null = null

      // 通过IPC调用主进程的AI服务
      switch (action) {
        case 'polish':
          result = await window.electronAPI.ai.polish(text, options)
          break
        case 'expand':
          result = await window.electronAPI.ai.expand(text, options)
          break
        case 'translate':
          result = await window.electronAPI.ai.translate(text, options.targetLang || 'English', options)
          break
        case 'summarize':
          result = await window.electronAPI.ai.summarize(text, options)
          break
        case 'continue':
          result = await window.electronAPI.ai.continueWriting(text, options.context || '', options)
          break
        case 'generate':
          result = await window.electronAPI.ai.generateContent(text, options)
          break
        case 'fixGrammar':
          result = await window.electronAPI.ai.fixGrammar(text, options)
          break
        case 'changeTone':
          result = await window.electronAPI.ai.changeTone(text, options.tone || 'neutral', options)
          break
        case 'formatMarkdown':
          result = await window.electronAPI.ai.formatMarkdown(text)
          break
        case 'extractKeywords':
          const keywords = await window.electronAPI.ai.extractKeywords(text)
          result = keywords.join(', ')
          break
        case 'generateOutline':
          result = await window.electronAPI.ai.generateOutline(text, options)
          break
        case 'improveSEO':
          result = await window.electronAPI.ai.improveSEO(text)
          break
        default:
          throw new Error(`Unsupported action: ${action}`)
      }

      clearInterval(progressInterval)

      setState(prev => ({
        ...prev,
        isLoading: false,
        result,
        progress: 100,
      }))

      return result

    } catch (error) {
      clearInterval(progressInterval)

      const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'

      setState(prev => ({
        ...prev,
        isLoading: false,
        error: errorMessage,
        progress: 0,
      }))

      return null
    }
  }, [initializeAI])

  // 流式AI操作
  const executeAIActionStream = useCallback(async (
    action: AIAction,
    text: string,
    options: AIWriterOptions & { targetLang?: string } = {},
    onChunk?: (chunk: string) => void
  ): Promise<string | null> => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
    }

    abortControllerRef.current = new AbortController()

    setState(prev => ({
      ...prev,
      isLoading: true,
      error: null,
      result: null,
      progress: 0,
      currentAction: getActionDisplayName(action),
    }))

    try {
      await initializeAI()

      let fullResult = ''

      // 通过IPC调用流式AI服务
      if (window.electronAPI.ai.streamAction) {
        const stream = await window.electronAPI.ai.streamAction(action, text, options)

        for await (const chunk of stream) {
          if (abortControllerRef.current?.signal.aborted) {
            break
          }

          fullResult += chunk
          onChunk?.(chunk)

          setState(prev => ({
            ...prev,
            result: fullResult,
            progress: Math.min(prev.progress + 5, 90),
          }))
        }
      } else {
        // 回退到非流式调用
        fullResult = await executeAIAction(action, text, options) || ''
      }

      setState(prev => ({
        ...prev,
        isLoading: false,
        result: fullResult,
        progress: 100,
      }))

      return fullResult

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'

      setState(prev => ({
        ...prev,
        isLoading: false,
        error: errorMessage,
        progress: 0,
      }))

      return null
    }
  }, [initializeAI, executeAIAction])

  // 取消操作
  const cancel = useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
    }

    setState(prev => ({
      ...prev,
      isLoading: false,
      error: 'Operation cancelled',
      progress: 0,
    }))
  }, [])

  // 重置状态
  const reset = useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort()
    }

    setState({
      isLoading: false,
      result: null,
      error: null,
      progress: 0,
      currentAction: '',
    })
  }, [])

  // 获取可用的AI功能
  const getAvailableFeatures = useCallback(async (): Promise<string[]> => {
    try {
      if (window.electronAPI.ai.getAvailableFeatures) {
        return await window.electronAPI.ai.getAvailableFeatures()
      }
      return [
        'polish', 'expand', 'translate', 'summarize', 'continue',
        'generate', 'fixGrammar', 'changeTone', 'formatMarkdown',
        'extractKeywords', 'generateOutline', 'improveSEO'
      ]
    } catch (error) {
      console.error('Failed to get available features:', error)
      return []
    }
  }, [])

  // 测试AI连接
  const testConnection = useCallback(async (): Promise<boolean> => {
    try {
      if (window.electronAPI.ai.testConnection) {
        return await window.electronAPI.ai.testConnection()
      }
      return true
    } catch (error) {
      console.error('AI connection test failed:', error)
      return false
    }
  }, [])

  // 获取操作显示名称
  const getActionDisplayName = (action: AIAction): string => {
    const names: Record<AIAction, string> = {
      polish: '润色文本',
      expand: '扩写内容',
      translate: '翻译文本',
      summarize: '生成摘要',
      continue: '续写内容',
      generate: '生成内容',
      fixGrammar: '修正语法',
      changeTone: '调整语气',
      formatMarkdown: '格式化Markdown',
      extractKeywords: '提取关键词',
      generateOutline: '生成大纲',
      improveSEO: 'SEO优化',
    }
    return names[action] || action
  }

  return {
    // 状态
    ...state,

    // 方法
    executeAIAction,
    executeAIActionStream,
    cancel,
    reset,
    getAvailableFeatures,
    testConnection,
    initializeAI,

    // 便捷方法
    polish: (text: string, options?: AIWriterOptions) =>
      executeAIAction('polish', text, options),

    expand: (text: string, options?: AIWriterOptions) =>
      executeAIAction('expand', text, options),

    translate: (text: string, targetLang: string, options?: AIWriterOptions) =>
      executeAIAction('translate', text, { ...options, targetLang }),

    summarize: (text: string, options?: AIWriterOptions) =>
      executeAIAction('summarize', text, options),

    continue: (text: string, context?: string, options?: AIWriterOptions) =>
      executeAIAction('continue', text, { ...options, context }),

    generate: (prompt: string, options?: AIWriterOptions) =>
      executeAIAction('generate', prompt, options),

    fixGrammar: (text: string, options?: AIWriterOptions) =>
      executeAIAction('fixGrammar', text, options),

    changeTone: (text: string, tone: string, options?: AIWriterOptions) =>
      executeAIAction('changeTone', text, { ...options, tone }),

    formatMarkdown: (text: string) =>
      executeAIAction('formatMarkdown', text),

    extractKeywords: (text: string) =>
      executeAIAction('extractKeywords', text),

    generateOutline: (topic: string, options?: AIWriterOptions) =>
      executeAIAction('generateOutline', topic, options),

    improveSEO: (text: string) =>
      executeAIAction('improveSEO', text),
  }
}